package com.ncu.weatherchina;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.ncu.weatherchina.CityBean.City;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import pl.com.salsoft.sqlitestudioremote.SQLiteStudioService;

public class MainActivity extends AppCompatActivity {
    private String default_city_code;
    private TextView addressTxt;
    private TextView updated_atTxt;
    private TextView statusTxt;
    private TextView tempTxt;
    private TextView temp_minTxt;
    private TextView temp_maxTxt;
    private TextView sunriseTxt;
    private TextView sunsetTxt;
    private TextView windTxt;
    private TextView windDirText;
    private TextView humidityTxt;
    private Button aqi;
    private TextView pm25;
    private TextView air_quality;
    private TextView weatherIconText;
    private WeatherInfo info;
    private ForecastAdapter mlistAdapter;
    private ZhiShuAdapter mlistAdapter2;
    private ListView mListView;
    private ListView mListView2;
    private boolean flag=false;
    private List<City> cityList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //添加调试的信息
        SQLiteStudioService.instance().start(this);
        WidgetRegist();
        SharedPreferences sp = getSharedPreferences("pppp", Context.MODE_PRIVATE);
        if(sp.getString("code", null)!=null){
            default_city_code =  sp.getString("code", null);
            new weatherTask().execute();
        }
        aqi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(flag == false){
                    flag = true;
                    mListView2.setVisibility(View.GONE);
                    mListView.setVisibility(View.VISIBLE);
                    aqi.setText("适宜指数");
                }else{
                    flag = false;
                    mListView.setVisibility(View.GONE);
                    mListView2.setVisibility(View.VISIBLE);
                    aqi.setText("未来天气");
                }
            }
        });
        addressTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, OneActivity.class);
                intent.putExtra("list", (Serializable) cityList);
                startActivityForResult(intent,1);
            }
        });
    }
    public void WidgetRegist(){
        addressTxt=findViewById(R.id.address);
        updated_atTxt=findViewById(R.id.updated_at);
        weatherIconText=findViewById(R.id.weather_icon);
        statusTxt=findViewById(R.id.status);
        tempTxt=findViewById(R.id.temp);
        temp_maxTxt=findViewById(R.id.temp_max);
        temp_minTxt=findViewById(R.id.temp_min);
        sunriseTxt=findViewById(R.id.sunrise);
        sunsetTxt=findViewById(R.id.sunset);
        windTxt=findViewById(R.id.wind);
        windDirText=findViewById(R.id.wind_dir);
        humidityTxt=findViewById(R.id.humidity);
        aqi=findViewById(R.id.aqi);
        pm25=findViewById(R.id.pm25);
        air_quality=findViewById(R.id.air_quality);
        mListView = findViewById(R.id.list_forecast);
        mListView2 = findViewById(R.id.list_zhishu);
        new weatherTask().execute();
        aqi.setText("适宜指数");
    }
    public void getFromAssetes(String fileName){
        try{
            InputStream in = getResources().getAssets().open(fileName);
            StringBuffer buffer = new StringBuffer();
            BufferedReader re = new BufferedReader(new InputStreamReader(in));
            int k = 1;
            while(re.readLine()!=null){
                String str = re.readLine().trim();//忽略前后空白
                String [] arr = str.split("\\s+");
                City city = new City();
                //将读取的数据放入到这个里面
                city.setId(k);
                city.setProvince(arr[0]);
                city.setCity(arr[1]);
                city.setCounty(arr[2]);
                city.setCode(arr[3]);
                //储存到数据库中
                city.save();
                cityList.add(city);
                k++;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    class weatherTask extends AsyncTask<WeatherInfo,Void,WeatherInfo>{

        @Override
        protected void onPreExecute() {
            //准备工作
            super.onPreExecute();
            findViewById(R.id.loader).setVisibility(View.VISIBLE);
            findViewById(R.id.mainContainer).setVisibility(View.GONE);
            findViewById(R.id.errorText).setVisibility(View.GONE);
            cityList = new ArrayList<City>();
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        protected WeatherInfo doInBackground(WeatherInfo... weatherInfos) {

            Connector.getDatabase();
            cityList=DataSupport.findAll(City.class);
            if(cityList.size()==0) {
                //读取txt文件内容
                getFromAssetes("city_code.txt");
                //删除数据库的数据
                //DataSupport.deleteAll(City.class);
            }else{
                Log.d("1111","数据库不为空");
                //DataSupport.deleteAll(City.class);
            }

            return RemoteDataParser.parseRemoteData(default_city_code);
        }

        @SuppressLint("SetTextI18n")
        @Override
        protected void onPostExecute(WeatherInfo result) {
            try {
                info = result;
                addressTxt.setText(result.getCity());
                Time t = new Time();
                t.setToNow();
                int year=t.year;
                int month = t.month+1;
                int day=t.monthDay;
                String updateTime = "更新 "+year+"-"+month+"-"+day+" "+result.getUpdate_time();
                updated_atTxt.setText(updateTime);

                String DayType = result.getForecastInfoList().get(1).getDay_type();
                Util.setWeatherIcon(getApplicationContext(),DayType,weatherIconText);
                statusTxt.setText(DayType);

                Typeface light = Typeface.createFromAsset(getAssets(),"font/Quicksand-Light.otf");
                tempTxt.setTypeface(light);
                tempTxt.setText(result.getCurrent_temp()+"°");

                temp_minTxt.setText(result.getForecastInfoList().get(1).getTemp_min());
                temp_maxTxt.setText(result.getForecastInfoList().get(1).getTemp_max());
                sunriseTxt.setText(result.getSun_set());
                sunsetTxt.setText(result.getSun_down());
                windTxt.setText(result.getCurrent_wind_force());
                windDirText.setText(result.getCurrent_wind_dir());
                humidityTxt.setText(result.getCurrent_humidity());


                mlistAdapter= new ForecastAdapter(MainActivity.this,result.forecastList);
                mListView.setAdapter(mlistAdapter);
                mlistAdapter2= new ZhiShuAdapter(MainActivity.this,result.indexlist);
                mListView2.setAdapter(mlistAdapter2);


                pm25.setText("PM2.5 "+result.getCurrent_pm25());
                air_quality.setText("空气 "+result.getAir_quality());
                findViewById(R.id.loader).setVisibility(View.GONE);
                findViewById(R.id.mainContainer).setVisibility(View.VISIBLE);
            }catch (Exception e){
                findViewById(R.id.loader).setVisibility(View.GONE);
                findViewById(R.id.errorText).setVisibility(View.VISIBLE);
                default_city_code = "101010100";
                new weatherTask().execute();
            }
        }
    }
    @Override
    protected  void onActivityResult(int requestCode,int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:{
                if(resultCode==RESULT_OK){
                    String returndata = data.getStringExtra("data_return");
                    if(returndata=="1"){
                        Log.d("111","用户未正确选择");
                    }else{
                        //刷新一下更换代码
                        default_city_code = returndata;
                        Log.d("1111",returndata);
                        new weatherTask().execute();
                    }
                }
                break;
            }
            default:
        }
    }
    //程序关闭的时候
    @Override
    public void onStop() {
        super.onStop();
        SharedPreferences sp = getSharedPreferences("pppp", Context.MODE_PRIVATE);
        sp.edit()
                .putString("code", default_city_code)
                .commit();
        //unbindService(conn);
    }
}
